package com.dinadi.yidi.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.DailyProductAdapter;
import com.dinadi.yidi.adapter.ProductInformationAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.AttentionBean;
import com.dinadi.yidi.bean.CollectionBean;
import com.dinadi.yidi.bean.CommentBean;
import com.dinadi.yidi.bean.CommentListRequest;
import com.dinadi.yidi.bean.CommentRequest;
import com.dinadi.yidi.bean.DailyProductBean;
import com.dinadi.yidi.bean.ImgsBean;
import com.dinadi.yidi.bean.ImgsRequest;
import com.dinadi.yidi.bean.MessageBean;
import com.dinadi.yidi.bean.ProductAattributesBean;
import com.dinadi.yidi.bean.ProductIDBean;
import com.dinadi.yidi.bean.ProductIDRequest;
import com.dinadi.yidi.bean.ProductIDRequestEntity;
import com.dinadi.yidi.bean.SkuListBean;
import com.dinadi.yidi.bean.UserInformationBean;
import com.dinadi.yidi.bean.WriteCommentsBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.ui.view.CommonDialogUtils;
import com.dinadi.yidi.ui.view.FlyBanner;
import com.dinadi.yidi.ui.view.MyListView;
import com.dinadi.yidi.ui.view.ShareMenuPopupWindow;
import com.dinadi.yidi.ui.view.ShowImageWebView;
import com.dinadi.yidi.utils.Constant;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2017/4/7   产品详情
 * Time: 17:01
 */

public class ProductDetailsActivity extends BaseActivity {
    private View view;
    private Button btn_title_right;
    private TextView tvTitle, tv_more, product_title, product_price, designer_name, designer_nick_name, designer_signature, designer_flow_num;
    private TextView num, txt_product_choice, original_price, txt_product_price;
    private ImageView designer_follow, img_no_comment, collection, goto_customer_service, by_now, img_shopping_cart;
    private ImageView delete_num, add_num, give_gift;
    private ShowImageWebView activity_help_web;
    private CircleImageView head_img;
    private ListView customListView;
    private ImageView img_add_shopping_cart, goto_comment;
    private FlyBanner design_view_pager;
    private ProgressBar pbLoad;
    /*添加listview头部尾部*/
    private View headView, footView;
    /*评论*/
    private DailyProductAdapter adapter;
    private ShareMenuPopupWindow selectImage;
    private List<CommentRequest> mList = new ArrayList<>();
    private int itemIndex;
    private int page = 1;
    private String subjectProductId, productId, isCollect, title, coverImg, price;
    /*联系电话*/
    private String phoneNumber = "15101570380";
    /*是否第一次进入页面*/
    private boolean isfirst = true;
    private String userId, token, status;
    /*是否被关注*/
    private String haveFlow;//0否  1.是
    /*设计师id*/
    private String designerUserId;
    /*判断是否登陆*/
    private boolean loginState;
    /*产品数量*/
    private int number = 1;
    /*商品属性*/
    private ProductInformationAdapter productAdapter;
    private List<ProductIDRequestEntity> productList = new ArrayList<>();
    private List<SkuListBean> skuList = new ArrayList<>();
    private int sharePosition;
    /*库存数量*/
    private int stock;
    /*是否提示让选择商品属性*/
    private boolean isShowToast = true;
    /*地址信息*/
    private String nameValue, skuId;
    private int isShoppingCart; //0  购买   1加入购物车   2送礼
    private UtilPopupWindow popupWindow;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(ProductDetailsActivity.this).inflate(R.layout.activity_daily_product, null);
        return view;
    }

    private Handler handler = new Handler();

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        customListView = (ListView) view.findViewById(R.id.custom_listview);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.text_creative_product));
        btn_title_right = (Button) view.findViewById(R.id.btn_title_right);
        btn_title_right.setBackgroundResource(R.drawable.product_details_icon_share);
        headView = getLayoutInflater().inflate(R.layout.listview_designer_head, customListView, false);
        footView = getLayoutInflater().inflate(R.layout.load_more_footview_layout, customListView, false);
        customListView.addHeaderView(headView);
        customListView.addFooterView(footView);
        tv_more = (TextView) customListView.findViewById(R.id.tvLoadText);
        img_no_comment = (ImageView) findViewById(R.id.img_no_comment);
        customListView.setDivider(null);
        pbLoad = (ProgressBar) view.findViewById(R.id.pbLoad);
        design_view_pager = (FlyBanner) view.findViewById(R.id.design_view_pager);
        product_title = (TextView) view.findViewById(R.id.product_title);
        product_price = (TextView) view.findViewById(R.id.product_price);
        original_price = (TextView) view.findViewById(R.id.original_price);
        activity_help_web = (ShowImageWebView) view.findViewById(R.id.activity_help_web);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        designer_name = (TextView) view.findViewById(R.id.designer_name);
        designer_nick_name = (TextView) view.findViewById(R.id.designer_nick_name);
        designer_signature = (TextView) view.findViewById(R.id.designer_signature);
        designer_flow_num = (TextView) view.findViewById(R.id.designer_flow_num);
        designer_follow = (ImageView) view.findViewById(R.id.designer_follow);
        goto_comment = (ImageView) view.findViewById(R.id.goto_comment);
        collection = (ImageView) view.findViewById(R.id.collection);
        goto_customer_service = (ImageView) view.findViewById(R.id.goto_customer_service);
        by_now = (ImageView) view.findViewById(R.id.by_now);
        img_shopping_cart = (ImageView) view.findViewById(R.id.img_shopping_cart);
        img_add_shopping_cart = (ImageView) view.findViewById(R.id.img_add_shopping_cart);
        give_gift = (ImageView) view.findViewById(R.id.give_gift);

        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        activity_help_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            // 网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                activity_help_web.getSettings().setJavaScriptEnabled(true);
                // web 页面加载完成，添加监听图片的点击 js 函数
                activity_help_web.setImageClickListner();
                //解析 HTML
                activity_help_web.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(ProductDetailsActivity.this, "请检查您的网络设置", Toast.LENGTH_SHORT).show();
            }
        });

        adapter = new DailyProductAdapter(ProductDetailsActivity.this, mList);
        customListView.setAdapter(adapter);
        MobclickAgent.onEvent(ProductDetailsActivity.this, "ProductDetails", "商品点击");
    }

    @Override
    protected void initListener() {

        customListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {


                int lastIndex = adapter.getCount() - 1;
                int item = lastIndex + 2;
                Log.d("TAG", "滑动的Item" + item);
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && itemIndex == item) {
                    isfirst = false;
                    loadData();


                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                itemIndex = firstVisibleItem + visibleItemCount - 1;
                Log.d("TAG", "滑动" + itemIndex);
            }
        });
        registerClickListener(btn_title_right, goto_comment, designer_follow, collection, head_img,
                goto_customer_service, by_now, img_shopping_cart, img_add_shopping_cart,give_gift);

    }

    private void loadData() {
        tv_more.setText("正在加载...");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_more.setText("上拉加载");
                page = page + 1;
                getComment();
            }
        }, 2000);

    }


    @Override
    public void onResume() {
        super.onResume();

        userId = SharePreferencesHelper.getInstance(this).getString("userId");
        token = SharePreferencesHelper.getInstance(this).getString("token");
        loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");

    }

    @Override
    protected void initData() {
        mList.clear();
        activity_help_web.clearImgs();
        adapter.notifyDataSetChanged();
        userId = SharePreferencesHelper.getInstance(ProductDetailsActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(ProductDetailsActivity.this).getString("token");
        loginState = SharePreferencesHelper.getInstance(ProductDetailsActivity.this).getBoolean("loginState");
        Intent intent = getIntent();
        String everyday = intent.getStringExtra("everyday");
        subjectProductId = intent.getStringExtra("subjectProductId");
        productId = intent.getStringExtra("productId");
        if (everyday != null && everyday.equals("0")) {
            getDailyProduct();
        } else {
            getProduct();
        }

    }

    /*产品详情*/
    private void getProduct() {
        DailyProductBean bean = new DailyProductBean();
        bean.setProductId(productId);
        bean.setToken(token);
        bean.setUserId(userId);
        CommonInterface dailyProductInterface = new CommonInterface(ProductDetailsActivity.this, httpListener);
        dailyProductInterface.getInterface("12003", JSON.toJSONString(bean));
    }

    /*每日产品*/
    private void getDailyProduct() {
        // showLoadingDialog(getResources().getString(R.string.dialog_text));
        DailyProductBean bean = new DailyProductBean();
        bean.setSubjectId(subjectProductId);
        bean.setToken(token);
        CommonInterface dailyProductInterface = new CommonInterface(ProductDetailsActivity.this, dailyHttpListener);
        dailyProductInterface.getInterface("14006", JSON.toJSONString(bean));
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.goto_comment:
                /*评论*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(ProductDetailsActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    showEditPopup();
                }

                break;
            case R.id.designer_follow:
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(ProductDetailsActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    if (haveFlow.equals("0")) {
                        //没有被关注所以去关注;//状态 1-关注 0-取消关注"
                        designer_follow.setImageResource(R.drawable.icon_follow_selected_big);
                        status = "1";

                    } else {
                        //已经关注了所以取消
                        designer_follow.setImageResource(R.drawable.icon_follow_pressed_big);
                        status = "0";
                    }
                    AttentionBean bean = new AttentionBean();
                    bean.setUserId(userId);
                    bean.setTargerUserId(designerUserId);
                    bean.setStatus(status);
                    bean.setToken(token);
                    CommonInterface attentionInterface = new CommonInterface(ProductDetailsActivity.this, AttentionHttpListener);
                    attentionInterface.getInterface("11009", JSON.toJSONString(bean));
                }

                break;
            case R.id.collection:
                 /*收藏*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(ProductDetailsActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    if (isCollect.equals("0")) {
                        /*没有收藏 进行收藏*/
                        isCollect = "1";
                        //   collection.setImageResource(R.drawable.product_icon_collection_selected);
                    } else {
                        isCollect = "0";
                        //  collection.setImageResource(R.drawable.product_icon_collection);
                    }
                    CollectionBean bean = new CollectionBean();
                    bean.setToken(token);
                    bean.setStatus(isCollect);
                    bean.setUserId(userId);
                    bean.setImgId(coverImg);
                    bean.setTargetId(productId);
                    bean.setTitle(title);
                    bean.setType("1");
                    CommonInterface collectionInterface = new CommonInterface(this, collectionHttpListener);
                    collectionInterface.getInterface("15003", JSON.toJSONString(bean));
                }


                break;
            case R.id.head_img:
                Intent intent = new Intent();
                intent.setClass(ProductDetailsActivity.this, DesignerHmePageActivity.class);
                intent.putExtra("dUserId", designerUserId);
                intent.putExtra("type", "2");
                startActivity(intent);
                break;
            case R.id.goto_customer_service:
                /*客服*/
                CommonDialogUtils myDialog = new CommonDialogUtils(ProductDetailsActivity.this);
                myDialog.setContent("拨号：" + phoneNumber);
                myDialog.setDialogCallback(phone_Dialogcallback);
                myDialog.show();
                break;
            case R.id.by_now:
                /*立即购买*/

                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    isShoppingCart = 0;
                    byNowBox();
                }
                break;
            case R.id.give_gift:
                /*送礼*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    isShoppingCart = 2;
                    byNowBox();
                }
                break;
            case R.id.btn_title_right:
                 /*分享*/
                ShowPickDialog();
                break;
            case R.id.img_shopping_cart:
                /*查看购物车*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    Intent shoppingCartIntent = new Intent(ProductDetailsActivity.this, MyShoppingCartsActivity.class);
                    startActivity(shoppingCartIntent);
                }
                break;
            case R.id.img_add_shopping_cart:
                /*加入购物车*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    isShoppingCart = 1;
                    byNowBox();
                }
                break;
            default:
                break;

        }

    }

    /*购买框*/
    private void byNowBox() {
        //当然是先初始化popupWindow
        popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.popupwindow_buy_box, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_daily_product, null);
        popupWindow.setPopupWindow(ProductDetailsActivity.this, (windowHeight / 4) * 3, layout, layout2, Gravity.BOTTOM);
        ImageView img_confirm_selection = (ImageView) layout.findViewById(R.id.img_confirm_selection);
        ImageView img_dimss_pupopwindow = (ImageView) layout.findViewById(R.id.img_dimss_pupopwindow);
        ImageView img_product = (ImageView) layout.findViewById(R.id.img_product);
        TextView txt_product_name = (TextView) layout.findViewById(R.id.txt_product_name);
        txt_product_price = (TextView) layout.findViewById(R.id.txt_product_price);
        MyListView lv_product_attribute = (MyListView) layout.findViewById(R.id.lv_product_attribute);
        delete_num = (ImageView) layout.findViewById(R.id.delete_num);
        add_num = (ImageView) layout.findViewById(R.id.add_num);
        num = (TextView) layout.findViewById(R.id.num);
        txt_product_choice = (TextView) layout.findViewById(R.id.txt_product_choice);
        lv_product_attribute.setDivider(null);
        lv_product_attribute.setEnabled(false);
        ImageUtils.loadImageView(ProductDetailsActivity.this, coverImg, img_product);
        txt_product_name.setText(title);
        txt_product_price.setText("¥" + price);
        productAdapter = new ProductInformationAdapter(ProductDetailsActivity.this, productList, skuList);
        lv_product_attribute.setAdapter(productAdapter);
          /*商品信息*/
        productInformation();
        number = 1;
        num.setText(number + "");
        isShowToast = true;

        /**为1的时候不能点*/
        delete_num.setClickable(false);
        delete_num.setImageResource(R.drawable.product_tab_reduce_select);

        delete_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete_num.setImageResource(R.drawable.product_tab_reduce_default);
                if (number == 1) {
                    delete_num.setClickable(false); //为1的时候减不能点
                    delete_num.setImageResource(R.drawable.product_tab_reduce_select);
                } else {
                    add_num.setClickable(true);
                    add_num.setImageResource(R.drawable.product_tab_plus_default);
                    number--;
                }
                num.setText(number + "");
            }
        });
        add_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (number != 1) {
                    delete_num.setClickable(true);
                    delete_num.setImageResource(R.drawable.product_tab_reduce_default);
                }
                if (isShowToast) {
//                    ToastUtil.showToast("请选择产品参数");
                    Toast.makeText(ProductDetailsActivity.this, "请选择产品参数", Toast.LENGTH_SHORT).show();
                } else {
                    if (number > stock || number == stock) {
                        number = stock;
                        add_num.setClickable(false);
                        add_num.setImageResource(R.drawable.product_tab_plus_select);
//                        toast("没有多余的库存啦");
                        Toast.makeText(ProductDetailsActivity.this, "没有多余的库存啦", Toast.LENGTH_SHORT).show();
                    } else {
                        number++;
                        delete_num.setClickable(true);
                        delete_num.setImageResource(R.drawable.product_tab_reduce_default);
                    }
                }

                num.setText(number + "");
            }
        });


        img_confirm_selection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*确认选择*/
                if (isShowToast) {
                    Toast.makeText(ProductDetailsActivity.this, "请选择产品参数", Toast.LENGTH_SHORT).show();
                } else {
                    if (isShoppingCart == 0) {
                        /*进行购买*/
                        Intent intent = new Intent(ProductDetailsActivity.this, OrderDetailsActivity.class);
                        intent.putExtra("nameValue", nameValue);
                        intent.putExtra("quantity", num.getText().toString());
                        intent.putExtra("token", token);
                        intent.putExtra("skuId", skuId);
                        startActivity(intent);
                        isShowToast = true;
                        popupWindow.dismiss();
                    } else if (isShoppingCart == 1) {
                        /*加入购物车*/
                        MessageBean shoppingCartBean = new MessageBean();
                        shoppingCartBean.setSkuId(skuId);
                        shoppingCartBean.setQuantity(num.getText().toString());
                        shoppingCartBean.setNameValue(nameValue);
                        shoppingCartBean.setUserId(userId);
                        shoppingCartBean.setProductId(productId);
                        shoppingCartBean.setToken(token);
                        CommonInterface commonInterface = new CommonInterface(ProductDetailsActivity.this, shoppingCartHttpListener);
                        commonInterface.getInterface("16034", JSON.toJSONString(shoppingCartBean));
                    }else if(isShoppingCart == 2){
                        /*送礼*/
                        Intent intent =new Intent(ProductDetailsActivity.this,GiveGiftOrderDetailsActivity.class);
                        intent.putExtra("nameValue", nameValue);
                        intent.putExtra("quantity", num.getText().toString());
                        intent.putExtra("token", token);
                        intent.putExtra("skuId", skuId);
                        startActivity(intent);
                        isShowToast = true;
                        popupWindow.dismiss();
                    }

                }
            }
        });
        productAdapter.addListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number = 1;
                num.setText(number + "");
                delete_num.setClickable(false);
                add_num.setClickable(true);
                add_num.setImageResource(R.drawable.product_tab_plus_default);
                delete_num.setImageResource(R.drawable.product_tab_reduce_select);
                ProductAattributesBean[] beans = (ProductAattributesBean[]) v.getTag(R.id.attrValueArray);

                /*库存*/
                String key = "";
                for (ProductAattributesBean b : beans) {
                    if (b != null)
                        key += b.getAttrValue() + ",";

                }
                SkuListBean skuListBean = (SkuListBean) v.getTag(R.id.stock);
                stock = Integer.parseInt(skuListBean.getStock());
                skuId = skuListBean.getSkuId();

                if (!key.equals("") && beans.length != 0) {
                    nameValue = key.substring(0, key.length() - 1);
                    txt_product_choice.setText("已选：" + nameValue);
                    String skuPrice = skuListBean.getPrice();
                    if (skuPrice != null) {
                        txt_product_price.setText("¥" + skuPrice);
                    }

                } else {
                    txt_product_choice.setText("已选：");
                    txt_product_price.setText("¥" + price);

                }
                productAdapter.notifyDataSetChanged();

                /*只要有一个为空  代表有一个属性还没选择*/
                isShowToast = true;
                for (int i = 0; i < beans.length; i++) {

                    if (beans[i] == null) {
                        return;
                    }
                }
                isShowToast = false;
            }
        });
        img_dimss_pupopwindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private void productInformation() {
        productList.clear();
        ProductIDBean bean = new ProductIDBean();
        bean.setProductId(productId);
        CommonInterface productInformationInterface = new CommonInterface(ProductDetailsActivity.this, productHttpListener);
        productInformationInterface.getInterface("16001", JSON.toJSONString(bean));

    }

    HttpListener productHttpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);

            ProductIDRequest bean = JsonUtil.parseJsonToBean(response, ProductIDRequest.class);
            productList.addAll(bean.getProductAttrList());
            skuList.addAll(bean.getSkuList());
            productAdapter.notifyDataSetChanged();

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };


    /*评论的弹框*/
    private void showEditPopup() {
        //当然是先初始化popupWindow
        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_comment, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_daily_product, null);
        popupWindow.setPopupWindow(ProductDetailsActivity.this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);
        TextView canel = (TextView) layout.findViewById(R.id.canel);
        TextView release = (TextView) layout.findViewById(R.id.release);
        final EditText edit_comment = (EditText) layout.findViewById(R.id.edit_comment);
        canel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
           /*自动弹出键盘*/
        edit_comment.setFocusableInTouchMode(true);
        edit_comment.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) edit_comment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(edit_comment, 0);
                           }

                       },
                100);
        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = null;
                try {
                    content = URLEncoder.encode(edit_comment.getText().toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (content.length() < 1) {
                    toast("内容不能为空哦");
                } else {
                    WriteCommentsBean bean = new WriteCommentsBean();
                    bean.setTargetId(productId);
                    bean.setFromUserId(userId);
                    bean.setToUserId(designerUserId);
                    bean.setContent(content);
                    bean.setType("1");
                    bean.setToken(token);
                    CommonInterface writeCommentsInterface = new CommonInterface(ProductDetailsActivity.this, httpListener4);
                    writeCommentsInterface.getInterface("15002", JSON.toJSONString(bean));
                    popupWindow.dismiss();
                }

            }
        });
    }

    /*产品信息*/
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                ImgsBean imgsBean = JsonUtil.parseJsonToBean(response, ImgsBean.class);

                ArrayList<ImgsRequest> dataList = new ArrayList<>();
                dataList.addAll(imgsBean.getImgs());

                final List<String> imgesUrl = new ArrayList<>();


                for (int i = 0; i < dataList.size(); i++) {

                    imgesUrl.add(dataList.get(i).getImgSrc());

                }
                design_view_pager.setImagesUrl(imgesUrl);


                design_view_pager.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent = new Intent();
                        intent.putExtra(Constant.POSITION, position + "");
                        intent.putStringArrayListExtra(Constant.IMAGE_URL_ALL, (ArrayList<String>) imgesUrl);
                        intent.setClass(ProductDetailsActivity.this, ShowImageFromWebActivity.class);
                        startActivity(intent);

                    }
                });

                title = JsonUtil.getFieldValue(response, "title");
                product_title.setText(title);
                price = JsonUtil.getFieldValue(response, "price");
                String originalPrice = JsonUtil.getFieldValue(response, "originalPrice");
                product_price.setText("￥" + price);
                if (!price.equals(originalPrice)) {
                    original_price.setText("￥" + originalPrice);
                    original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
                }
                String htmlPath = JsonUtil.getFieldValue(response, "htmlPath");
                activity_help_web.loadUrl(htmlPath);
                coverImg = JsonUtil.getFieldValue(response, "coverImg");
                /*设计师的id*/
                designerUserId = JsonUtil.getFieldValue(response, "userId");
                getDegisner();

                /*评论id  */
                productId = JsonUtil.getFieldValue(response, "productId");
               /*是否收藏 0 否  1 是*/
                isCollect = JsonUtil.getFieldValue(response, "hasCollect");
                if (isCollect.equals("0")) {
                    collection.setImageResource(R.drawable.product_icon_collection);
                } else {
                    collection.setImageResource(R.drawable.product_icon_collection_selected);
                }
                String stock = JsonUtil.getFieldValue(response, "stock");
                if (stock.equals("0")) {
                   /*没有库存*/
                    by_now.setImageResource(R.drawable.img_add_shopping_cart_no);
                    by_now.setOnClickListener(null);
                    img_add_shopping_cart.setImageResource(R.drawable.product_tab_sell_out);
                    img_add_shopping_cart.setOnClickListener(null);
                    give_gift.setImageResource(R.drawable.img_no_give_gift);
                    give_gift.setOnClickListener(null);


                }

            } else {
                //  closeLoadingDialog();
                toast("获取信息失败");
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            //    closeLoadingDialog();
            toast("获取信息失败");
        }

    };
    /*每日产品信息*/
    HttpListener dailyHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                String product = JsonUtil.getFieldValue(response, "product");

                /*评论id  */
                productId = JsonUtil.getFieldValue(product, "productId");
                getProduct();

            } else {
                // closeLoadingDialog();
                toast("获取信息失败");
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            // closeLoadingDialog();
            toast("获取信息失败");
        }

    };

    /*获取设计师的信息*/
    private void getDegisner() {
        UserInformationBean bean = new UserInformationBean();
        bean.setUserId(designerUserId);
        bean.setToken(token);
        CommonInterface userInformationInetrface = new CommonInterface(ProductDetailsActivity.this, httpListener2);
        userInformationInetrface.getInterface("11008", JSON.toJSONString(bean));

    }

    /*获取评论列表*/
    private void getComment() {

        CommentBean commentBean = new CommentBean();
        commentBean.setArticleId(productId);
        commentBean.setPageNum(page + "");
        commentBean.setPageSize("10");
        CommonInterface commentInterface = new CommonInterface(ProductDetailsActivity.this, httpListener3);
        commentInterface.getInterface("15001", JSON.toJSONString(commentBean));
    }

    /*获取设计师信息*/
    HttpListener httpListener2 = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                getComment();
                String headImg = JsonUtil.getFieldValue(response, "headImg");
                //头像地址
                if (!headImg.equals("")) {
                    ImageUtils.loadImageView(ProductDetailsActivity.this, headImg, head_img);
                } else {
                    ImageUtils.loadImageView(ProductDetailsActivity.this, R.drawable.me_img_default, head_img);
                }
                haveFlow = JsonUtil.getFieldValue(response, "haveFlow");
                if (haveFlow.equals("0")) {
                    designer_follow.setImageResource(R.drawable.icon_follow_pressed_big);
                } else {
                    designer_follow.setImageResource(R.drawable.icon_follow_selected_big);
                }
                String brandName = JsonUtil.getFieldValue(response, "brandName");
                designer_nick_name.setText(brandName);
                String userName = JsonUtil.getFieldValue(response, "userName");
                designer_name.setText(userName);
                String signature = JsonUtil.getFieldValue(response, "signature");
                designer_signature.setText(signature);
                String flowedNum = JsonUtil.getFieldValue(response, "flowedNum");
                designer_flow_num.setText(flowedNum);

                //   designerUserId = JsonUtil.getFieldValue(response, "userId");


            } else {
                toast("获取信息失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("获取信息失败");
        }
    };
    HttpListener httpListener3 = new HttpListener() {

        //显示评论
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                CommentListRequest commentList = JsonUtil.parseJsonToBean(response, CommentListRequest.class);
                //   mList = commentList.getCommentList();
                String commentId = JsonUtil.getFieldValue(response, "commentId");
                if (commentList.getCommentList().size() == 0) {
                    if (isfirst == true) {
                        tv_more.setVisibility(View.GONE);
                        pbLoad.setVisibility(View.GONE);
                        img_no_comment.setVisibility(View.VISIBLE);
                    } else {
                        tv_more.setVisibility(View.VISIBLE);
                        tv_more.setText("已显示全部评论");
                        tv_more.setTextColor(getResources().getColor(R.color.color_999999));
                        pbLoad.setVisibility(View.GONE);
                    }
                    page = 1;
                    customListView.setOnScrollListener(null);
                } else {
                    img_no_comment.setVisibility(View.GONE);
                }


                mList.addAll(commentList.getCommentList());
                adapter.notifyDataSetChanged();
            } else {
                toast("获取信息失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            toast("获取信息失败");
        }
    };

    /*写评论*/
    HttpListener httpListener4 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "1", "1", "评论成功");

                mList.clear();
                isfirst = false;
                getComment();
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("发表失败");
        }

    };
    /*是否取消关注*/
    HttpListener AttentionHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                if (status.equals("1")) {
                    IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "9", "1", "关注成功");
                } else {
                    IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "9", "2", "取消关注");
                }
                getDegisner();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("关注失败");
        }
    };
    /*取消收藏*/
    HttpListener collectionHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                if (isCollect.equals("0")) {
                    collection.setImageResource(R.drawable.product_icon_collection);
                    IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "3", "2", "取消收藏");
                    /*否*/
                } else if (isCollect.equals("1")) {
                    /*是*/
//                    View view = LayoutInflater.from(ProductDetailsActivity.this).inflate(R.layout.popupwindow_integral, null);
//                    new ToastUtils(ProductDetailsActivity.this, view, Toast.LENGTH_SHORT).show();
                    collection.setImageResource(R.drawable.product_icon_collection_selected);
                    IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "3", "1", "收藏成功");
                }
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("操作失败");
        }
    };

    /*添加购物车成功*/
    HttpListener shoppingCartHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                toast("添加购物车成功~");
//                mAnimImageView.setVisibility(View.VISIBLE);
//                mAnimImageView.startAnimation(mAnimation);
                popupWindow.dismiss();
            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("操作失败");
        }
    };

    CommonDialogUtils.Dialogcallback phone_Dialogcallback = new CommonDialogUtils.Dialogcallback() {
        @Override
        public void dialogdo() {
            //跳转登录页面
            //Android跳转到拨号界面，同时传递电话号码
            Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));//跳转到拨号界面，同时传递电话号码
            startActivity(dialIntent);

        }
    };

    //弹出分享框
    private void ShowPickDialog() {
        if (selectImage == null) {
            selectImage = new ShareMenuPopupWindow(this);
            selectImage.setOnShareClickListener(shareClickListener);
        }
        selectImage.showAtLocation(this.findViewById(R.id.linearlayout_base), Gravity.BOTTOM, 0, 0);
    }

    private ShareMenuPopupWindow.OnShareClickListener shareClickListener = new ShareMenuPopupWindow.OnShareClickListener() {

        @Override
        public void onShareClick(int position) {
            screenshot(position);
        }
    };

    private void share() {
        ShareAction shareAction = new ShareAction(this);
        UMImage thumb = new UMImage(this, coverImg);
        UMWeb web = new UMWeb("http://yididesign.cn/share_product.html?product_id=" + productId);
        web.setTitle(title);//标题
        web.setThumb(thumb);  //缩略图
        web.setDescription("分享内容");//描述
        if (sharePosition == 1) {
            shareAction.setCallback(umShareListener).withMedia(web).share();


        } else {
            shareAction.setCallback(umShareListener).withMedia(web).share();

        }
        switch (sharePosition) {

            case 0:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN); // 微信好友
                break;
            case 1:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);// 微信朋友圈
                break;

        }
        shareAction.share();
    }

    public void screenshot(int position) {
//        if (!LoadDialog.isShowProgressDialog()) {
//            LoadDialog.showProgressDialog(getActivity(), "制作分享数据...", false, false);
        sharePosition = position;
        share();

        //   }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
            selectImage.dismiss();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (loginState == true) {
                IntegralChangeInterface.IntegralChange(ProductDetailsActivity.this, userId, token, "4", "1", "分享成功啦");
            } else {
                ToastUtil.showToast("分享成功啦");
            }
            selectImage.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ProductDetailsActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
            selectImage.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ProductDetailsActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            selectImage.dismiss();
        }

    };

   /* @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && activity_help_web.canGoBack()) {
            activity_help_web.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
}
